package cn.com.shopec.erp.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.shopec.erp.common.constant.ProductSCMConstant;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.product.commo.ProductVoConvertor;
import cn.com.shopec.erp.product.dao.ICommodityDao;
import cn.com.shopec.erp.product.dao.IProdSpecValueDao;
import cn.com.shopec.erp.product.dao.IProdSupplierDao;
import cn.com.shopec.erp.product.dao.IProductDao;
import cn.com.shopec.erp.product.dao.IProductHistoryDao;
import cn.com.shopec.erp.product.entity.Commodity;
import cn.com.shopec.erp.product.entity.Product;
import cn.com.shopec.erp.product.entity.ProductHistory;
import cn.com.shopec.erp.product.model.BenefitProduct;
import cn.com.shopec.erp.product.service.IProductService;
import cn.com.shopec.erp.product.vo.ProductHistoryVo;
import cn.com.shopec.erp.product.vo.ProductVo1;
import cn.com.shopec.erp.purchase.vo.PurchaseRequisitionProductVo;

@Service
public class ProductServiceImpl implements IProductService {

    @Resource
    private ICommodityDao commodityDao;

    @Resource
    private IProductDao productDao;

    @Resource
    private IProductHistoryDao productHistoryDao;

    @Resource
    private ProductVoConvertor productVoConvertor;
    
    @Resource
    private IProdSpecValueDao prodSpecValueDao;
    
    @Resource
    private IProdSupplierDao prodSupplierDao;
    

    @Override
    @Transactional
    public void addProductHistory(ProductHistoryVo productHistoryVo) throws Exception {

        if (LogicUtil.isNotNull(productHistoryVo)) {
            this.productHistoryDao.save(this.productVoConvertor.convert2BaseProductHistory(productHistoryVo));
        }
    }

    @Override
    public PageFinder<ProductHistoryVo> getPagedProdHistory(ProductHistoryVo productHistoryVo, PageQuery pageQuery) {
        DetachedCriteria dc = this.productHistoryDao.createCriteria();

        if (LogicUtil.isNotNull(productHistoryVo)) {

            if (LogicUtil.isNotNullAndEmpty(productHistoryVo.getOpStartTime())
                    && LogicUtil.isNotNullAndEmpty(productHistoryVo.getOpEndTime())) {

                dc.add(Restrictions.between("opTime", productHistoryVo.getOpStartTime(),
                        productHistoryVo.getOpEndTime()));
            } else {
                if (LogicUtil.isNotNullAndEmpty(productHistoryVo.getOpStartTime())) {
                    dc.add(Restrictions.ge("opTime", productHistoryVo.getOpStartTime()));

                } else if (LogicUtil.isNotNullAndEmpty(productHistoryVo.getOpEndTime())) {
                    dc.add(Restrictions.le("opTime", productHistoryVo.getOpEndTime()));
                }
            }
        }

        // 按操作时间排序
        dc.addOrder(Order.desc("opTime"));

        PageFinder<ProductHistory> pagedProductHistorys = this.productHistoryDao.pagedByCriteria(dc,
                pageQuery.getPage(), pageQuery.getPageSize());

        return this.productVoConvertor.convert2ProductHistory(pagedProductHistorys);
    }

    @Override
    @Transactional
    public PageFinder<ProductVo1> getPagedProductListByProduct(ProductVo1 productVo1, PageQuery pageQuery)
            throws Exception {
        PageFinder<ProductVo1> pagedGoodsVos = null;

        DetachedCriteria dc = this.productDao.createCriteria();

        if (LogicUtil.isNotNull(productVo1)) {
        	if(LogicUtil.isNotNull(productVo1.getSupId())){
        		// dc.add(Restrictions.eq("commoNo", defectiveVo.getId()));
        		//dc.add(Restrictions.eq("supId", productVo1.getSupId().trim()));
        	}

            if (LogicUtil.isNotNullAndEmpty(productVo1.getCommoNo())) {
                dc.add(Restrictions.eq("commoNo", productVo1.getCommoNo().trim()));
            }
            if (LogicUtil.isNotNullAndEmpty(productVo1.getCommoName())) {
                String sql = "commo_no in(select commo_no from tbl_commodity t where t.commo_name like '%"
                        + productVo1.getCommoName().trim() + "%' and t.delete_flag=1 )";
                dc.add(Restrictions.sqlRestriction(sql));
            }
            if (LogicUtil.isNotNullAndEmpty(productVo1.getProdNo())) {
                dc.add(Restrictions.like("prodNo", "%" + productVo1.getProdNo().trim() + "%"));
            }
            if(LogicUtil.isNotNullAndEmpty(productVo1.getIsReturnedGoos())){
            /*	String sql="prod_no in(select prod_no from tbl_prod_supplier where is_returned_goods="+productVo1.getIsReturnedGoos();*/
            	String sql="prod_no in(select prod_no from tbl_prod_supplier where ";
            	if(LogicUtil.isNotNull(productVo1.getCode())){
//            		sql+=" and SUPPLIER_NO="+productVo1.getCode().trim();
            		sql+=" SUPPLIER_NO='"+ productVo1.getCode().trim()+"'";
            	}
            	sql+=")";
            	dc.add(Restrictions.sqlRestriction(sql));
            }
        }
        String sql = "commo_no in(select commo_no from tbl_commodity t where t.check_state=1 )";
        dc.add(Restrictions.sqlRestriction(sql));

        dc.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));

        PageFinder<Product> pagedProducts = this.productDao.pagedByCriteria(dc, pageQuery.getPage(),
                pageQuery.getPageSize());

        List<ProductVo1> productVoList = null;
        if (LogicUtil.isNotNull(pagedProducts)) {
            if (LogicUtil.isNotNullAndEmpty(pagedProducts.getData())) {
                pagedGoodsVos = this.productVoConvertor.convert2PagedProductVoPageFinder(pagedProducts);

                if (LogicUtil.isNotNullAndEmpty(pagedGoodsVos.getData())) {
                    productVoList = new ArrayList<ProductVo1>();
                    for (ProductVo1 productVo : pagedGoodsVos.getData()) {
                        Commodity commodity = this.commodityDao.findUniqueBy("commoNo", productVo.getCommoNo());
                        productVo.setCommoName(null == commodity ? "" : commodity.getCommoName());
                        productVoList.add(productVo);
                    }

                }
            }
        }
        pagedGoodsVos = new PageFinder<ProductVo1>(pagedProducts.getPageNo(), pagedProducts.getPageSize(),
                pagedProducts.getRowCount(), productVoList);

        return pagedGoodsVos;
    }

    @Override
    public PageFinder<ProductVo1> getPagedProductListByCommoNo(String commoNo, PageQuery pageQuery) throws Exception {

        DetachedCriteria dc = this.productDao.createCriteria();

        if (LogicUtil.isNotNullAndEmpty(commoNo)) {
            dc.add(Restrictions.eq("commoNo", commoNo.trim()));
            dc.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
            dc.addOrder(Order.asc("prodBarCode"));
        }

        PageFinder<Product> pagedProducts = this.productDao.pagedByCriteria(dc, pageQuery.getPage(),
                pageQuery.getPageSize());

        return this.productVoConvertor.convert2PagedProductVoPageFinder(pagedProducts);
    }

    @Override
    @Transactional
    public void delProduct(String prodNo) throws Exception {
    	DetachedCriteria criteria = this.productDao.createCriteria();
    	criteria.add(Restrictions.eq("prodNo", prodNo));
        criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));

        List<Product> productList = this.productDao.findByCriteria(criteria);
        
        if (productList.size() >0) {
        	Product product = productList.get(0);
            product.setDeleteFlag(SZSCMConstant.DELETE_FLAG_YES);
            this.prodSpecValueDao.deleteProdSpecValue(prodNo);
            this.productDao.update(product);
            //删除供应商价格设置
            this.prodSupplierDao.delectProdSuppliers(prodNo, null);
        }
    }

    @Override
    public String validationRepeatProdBarCode(String prodBarCode) {
        DetachedCriteria criteria = this.productDao.createCriteria();

        if (LogicUtil.isNotNullAndEmpty(prodBarCode)) {
            criteria.add(Restrictions.eq("prodBarCode", prodBarCode));
            criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));

            List<Product> productList = this.productDao.findByCriteria(criteria);
            if (productList.size() > 0) {
                return SZSCMConstant.SUCCESS;
            } else {
                return SZSCMConstant.FAIL;
            }
        }

        return SZSCMConstant.FAIL;
    }

    @Override
    public Product getProductIntfo(String prodNo) {
        Product product = null;

        DetachedCriteria criteria = this.productDao.createCriteria();
        criteria.add(Restrictions.eq("prodNo", prodNo));
        criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));

        List<Product> productList = this.productDao.findByCriteria(criteria);
        if (LogicUtil.isNotNullAndEmpty(productList)) {
            product = productList.get(0);
        }

        return product;
    }
    
    @Override
    public Product getProductIntfoByCommon(String commoNo) {
        Product product = null;

        DetachedCriteria criteria = this.productDao.createCriteria();
        criteria.add(Restrictions.eq("commoNo", commoNo));
        criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));

        List<Product> productList = this.productDao.findByCriteria(criteria);
        if (LogicUtil.isNotNullAndEmpty(productList)) {
            product = productList.get(0);
        }

        return product;
    }
    
    

    @Override
    public PageFinder<BenefitProduct> getPagedBenefitProductList(BenefitProduct benefitProduct, PageQuery pageQuery)
            throws Exception {
        DetachedCriteria dc = this.productDao.createCriteria();
        if (LogicUtil.isNotNull(benefitProduct)) {

            if (LogicUtil.isNotNullAndEmpty(benefitProduct.getCommoNo())) {
                dc.add(Restrictions.eq("commoNo", benefitProduct.getCommoNo().trim()));
            }
            if (LogicUtil.isNotNullAndEmpty(benefitProduct.getCommoName())) {
                String sql = "commo_no in(select commo_no from tbl_commodity t where t.commo_name like '%"
                        + benefitProduct.getCommoName().trim() + "%' and t.delete_flag=1 )";
                dc.add(Restrictions.sqlRestriction(sql));
            }
            if (LogicUtil.isNotNullAndEmpty(benefitProduct.getProdNo())) {
                dc.add(Restrictions.like("prodNo", "%" + benefitProduct.getProdNo().trim() + "%"));
            }
        }

        String sql = "commo_no in(select commo_no from tbl_commodity t where t.check_state=1 )";
        dc.add(Restrictions.sqlRestriction(sql));

        dc.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));

        PageFinder<Product> pagedProducts = this.productDao.pagedByCriteria(dc, pageQuery.getPage(),
                pageQuery.getPageSize());

        return this.productVoConvertor.convert2PagedBenefitProducts(pagedProducts);

    }
    
    /**
     * 根据供应商编号获取所对应的商品
     */
    @Override
    @Transactional
    public PageFinder<ProductVo1> getPagedProductListProduct(ProductVo1 productVo1, PageQuery pageQuery)
            throws Exception {
    	PageFinder<ProductVo1> pagedGoodsVos = null;
    	int count = prodSupplierDao.getProductsCountBySupNo(productVo1);
    	
    	PageFinder<ProductVo1> result = new PageFinder<ProductVo1>(pageQuery.getPage(),pageQuery.getPageSize(), count);
    	if (count > 0) {
    		List<ProductVo1> stockOutVos = productDao.queryPurchaseList(productVo1,result.getStartOfPage(), result.getPageSize());
    		result.setData(stockOutVos);
    		List<ProductVo1> productVoList = null;
    		 if (LogicUtil.isNotNullAndEmpty(result.getData())) {
//    			 pagedGoodsVos = this.productVoConvertor.convert2PagedProductVoPageFinder(result);
                 productVoList = new ArrayList<ProductVo1>();
                 for (ProductVo1 productVo : result.getData()) {
                     Commodity commodity = this.commodityDao.findUniqueBy("commoNo", productVo.getCommoNo());
                     productVo.setCommoName(null == commodity ? "" : commodity.getCommoName());
                     productVoList.add(productVo);
                 }
             }
    		 pagedGoodsVos = new PageFinder<ProductVo1>(result.getPageNo(), result.getPageSize(),
    				 result.getRowCount(), productVoList);
    	}
    	return pagedGoodsVos;
    }
   
}
